package com.xzh.mallorderapi.service.impl;

import com.mall.common.util.JsonResult;
import com.mall.model.Product;
import com.xzh.mallorderapi.dao.OrderItemMapper;
import com.xzh.mallorderapi.service.ProductServiceClient;
import com.xzh.mallorderspi.model.OrderItem;
import com.xzh.mallorderspi.service.OrderItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OrderItemServiceImpl implements OrderItemService {
    private OrderItemMapper orderItemMapper;
    private ProductServiceClient productServiceClient;

    @Autowired
    public OrderItemServiceImpl(OrderItemMapper orderItemMapper) {
        this.orderItemMapper = orderItemMapper;
    }

    @Autowired
    public void setProductServiceClient(ProductServiceClient productServiceClient) {
        this.productServiceClient = productServiceClient;
    }
    // 查询所有订单项
    @Override
    public List<OrderItem> findAll(OrderItem search) {
        return orderItemMapper.findAll(search);
    }
    // 保存订单项
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(OrderItem orderItem) {
        ResponseEntity<JsonResult<Product>> response = productServiceClient.findById(orderItem.getGoodId());
        JsonResult<Product> result = response.getBody();
        if(result== null||!result.isSuccess()){
            throw new RuntimeException("商品不存在");
        }

        Product product = result.getData();
        int qty = product.getStock() - orderItem.getCount();
        if(qty < 0){
            throw new RuntimeException("商品库存不足");
        }
        product.setStock(qty);
        orderItem.setGoodName(product.getName());
        orderItem.setGoodPic(product.getMainPicUrl());
        orderItem.setGoodDesc(product.getSummary());

        Product pt = new Product();
        pt.setId(product.getId());
        pt.setStock(qty);
        productServiceClient.deductStock(pt.getId(),qty);

        return orderItemMapper.insert(orderItem) > 0;
    }
    // 修改订单项
    @Override
    public boolean update(OrderItem orderItem) {
        return orderItemMapper.updateById(orderItem) > 0;
    }
    // 删除多项订单项
    @Override
    public int deleteByIds(List<Integer> ids) {
        return orderItemMapper.deleteByIds(ids);
    }
    // 删除订单项
    @Override
    public int deleteBy(OrderItem search) {
        return orderItemMapper.deleteById(search);
    }
}
